/**
 * 批改结果解析器
 * 解析和验证AI返回的JSON格式批改结果
 */

/**
 * 错误分类常量
 */
export const ERROR_CATEGORIES = {
  SPELLING: 'spelling',        // 错别字
  PUNCTUATION: 'punctuation',  // 标点符号
  GRAMMAR: 'grammar',          // 语法错误
  LOGIC: 'logic',              // 逻辑错误
  FORMAT: 'format',            // 格式错误
  LANGUAGE: 'language',        // 语言表达
  STRUCTURE: 'structure',      // 结构问题
  CONTENT: 'content',          // 内容问题
};

/**
 * 严重程度常量
 */
export const SEVERITY_LEVELS = {
  LOW: 'low',
  MEDIUM: 'medium',
  HIGH: 'high',
};

/**
 * 解析AI批改响应
 * @param {Object|string} aiResponse - AI返回的响应（可能是对象或JSON字符串）
 * @param {string} gradeLevel - 学段 (primary/middle/high)
 * @returns {Object} 解析后的标准化结果
 */
export function parseCorrection(aiResponse, gradeLevel = 'primary') {
  try {
    // 1. 预处理响应
    let parsedData;
    
    if (typeof aiResponse === 'string') {
      // 移除可能的markdown代码块标记（支持嵌套）
      let cleanedResponse = aiResponse.trim();
      
      // 移除外层的markdown代码块（如果有）
      while (cleanedResponse.startsWith('```')) {
        // 找到第一个换行符后的内容
        const firstNewline = cleanedResponse.indexOf('\n');
        if (firstNewline !== -1) {
          cleanedResponse = cleanedResponse.substring(firstNewline + 1).trim();
        }
        // 移除末尾的```
        if (cleanedResponse.endsWith('```')) {
          cleanedResponse = cleanedResponse.substring(0, cleanedResponse.lastIndexOf('```')).trim();
        }
      }
      
      parsedData = JSON.parse(cleanedResponse);
    } else if (typeof aiResponse === 'object' && aiResponse !== null) {
      parsedData = aiResponse;
    } else {
      throw new Error('AI响应必须是JSON字符串或对象');
    }

    // 2. 验证格式
    const validationResult = validateResultFormat(parsedData, gradeLevel);
    if (!validationResult.valid) {
      console.warn('批改结果格式验证失败:', validationResult.errors);
      // 尝试修复或使用默认值
      parsedData = repairResult(parsedData, gradeLevel);
    }

    // 3. 标准化结果
    const normalizedResult = normalizeResult(parsedData, gradeLevel);

    // 4. 提取和分类错误
    const errors = extractErrors(normalizedResult);

    // 5. 计算最终得分
    const finalScore = calculateFinalScore(normalizedResult);

    return {
      success: true,
      data: {
        ...normalizedResult,
        final_score: finalScore,
        error_count: errors.length,
        error_categories: categorizeErrors(errors),
      },
      parsed_at: new Date().toISOString(),
    };

  } catch (error) {
    console.error('批改结果解析失败:', error);
    
    // 返回默认结构
    return {
      success: false,
      error: {
        type: 'PARSE_ERROR',
        message: '批改结果解析失败',
        details: error.message,
      },
      data: getDefaultResult(gradeLevel),
      parsed_at: new Date().toISOString(),
    };
  }
}

/**
 * 验证结果格式
 * @param {Object} result - 待验证的结果
 * @param {string} gradeLevel - 学段
 * @returns {Object} { valid: boolean, errors: string[] }
 */
export function validateResultFormat(result, gradeLevel) {
  const errors = [];

  // 基础字段验证
  if (!result || typeof result !== 'object') {
    return { valid: false, errors: ['结果必须是对象'] };
  }

  // 验证grade_level
  if (!result.grade_level) {
    errors.push('缺少grade_level字段');
  } else if (!['primary', 'middle', 'high'].includes(result.grade_level)) {
    errors.push('grade_level必须是primary、middle或high之一');
  }

  // 验证score_breakdown
  if (!result.score_breakdown) {
    errors.push('缺少score_breakdown字段');
  } else {
    if (typeof result.score_breakdown.total_score !== 'number') {
      errors.push('total_score必须是数字');
    } else if (result.score_breakdown.total_score < 0 || result.score_breakdown.total_score > 100) {
      errors.push('total_score必须在0-100之间');
    }
  }

  // 根据学段验证特定字段
  if (gradeLevel === 'primary') {
    if (!result.basic_stats) {
      errors.push('小学批改结果缺少basic_stats字段');
    }
    if (!result.encouraging_comments) {
      errors.push('小学批改结果缺少encouraging_comments字段');
    }
  } else if (gradeLevel === 'middle') {
    if (!result.advanced_analysis) {
      errors.push('初中批改结果缺少advanced_analysis字段');
    }
    if (!result.strength_analysis) {
      errors.push('初中批改结果缺少strength_analysis字段');
    }
  } else if (gradeLevel === 'high') {
    if (!result.college_entrance_standard) {
      errors.push('高中批改结果缺少college_entrance_standard字段');
    }
    if (!result.depth_analysis) {
      errors.push('高中批改结果缺少depth_analysis字段');
    }
  }

  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * 提取错误信息
 * @param {Object} result - 批改结果
 * @returns {Array} 错误数组
 */
export function extractErrors(result) {
  const errors = [];

  // 从corrections字段提取
  if (Array.isArray(result.corrections)) {
    result.corrections.forEach((correction) => {
      errors.push({
        type: correction.type || correction.category || 'unknown',
        position: correction.position || '未指定',
        original: correction.original_text || correction.original_excerpt || '',
        suggested: correction.suggested_text || correction.suggested_revision || '',
        reason: correction.error_reason || correction.rationale || correction.improvement_reason || '',
        severity: correction.severity || 'medium',
      });
    });
  }

  // 从detailed_corrections字段提取（初中）
  if (Array.isArray(result.detailed_corrections)) {
    result.detailed_corrections.forEach((correction) => {
      errors.push({
        type: correction.category || 'unknown',
        position: correction.position || '未指定',
        original: correction.original_excerpt || '',
        suggested: correction.suggested_revision || '',
        reason: correction.rationale || '',
        severity: 'medium',
      });
    });
  }

  return errors;
}

/**
 * 计算最终得分
 * @param {Object} result - 批改结果
 * @returns {number} 最终得分（0-100）
 */
export function calculateFinalScore(result) {
  if (!result || !result.score_breakdown) {
    return 0;
  }

  const totalScore = result.score_breakdown.total_score;

  // 确保分数在有效范围内
  if (typeof totalScore !== 'number') {
    return 0;
  }

  return Math.max(0, Math.min(100, Math.round(totalScore)));
}

/**
 * 标准化结果
 * @param {Object} result - 原始结果
 * @param {string} gradeLevel - 学段
 * @returns {Object} 标准化后的结果
 */
export function normalizeResult(result, gradeLevel) {
  const normalized = {
    grade_level: result.grade_level || gradeLevel,
    score_breakdown: result.score_breakdown || {},
    corrections: result.corrections || result.detailed_corrections || [],
  };

  // 根据学段添加特定字段
  if (gradeLevel === 'primary') {
    normalized.basic_stats = result.basic_stats || {
      word_count: 0,
      paragraph_count: 0,
      error_count: 0,
    };
    normalized.encouraging_comments = result.encouraging_comments || '继续努力！';
    normalized.improvement_suggestions = result.improvement_suggestions || [];
    normalized.writing_tips = result.writing_tips || [];
  } else if (gradeLevel === 'middle') {
    normalized.advanced_analysis = result.advanced_analysis || {};
    normalized.strength_analysis = result.strength_analysis || '';
    normalized.weakness_analysis = result.weakness_analysis || '';
    normalized.specific_suggestions = result.specific_suggestions || [];
  } else if (gradeLevel === 'high') {
    normalized.college_entrance_standard = result.college_entrance_standard || {};
    normalized.depth_analysis = result.depth_analysis || {};
    normalized.artistic_evaluation = result.artistic_evaluation || {};
    normalized.college_prep_suggestions = result.college_prep_suggestions || [];
    normalized.model_essay_comparison = result.model_essay_comparison || '';
  }

  return normalized;
}

/**
 * 修复不完整的结果
 * @param {Object} result - 待修复的结果
 * @param {string} gradeLevel - 学段
 * @returns {Object} 修复后的结果
 */
function repairResult(result, gradeLevel) {
  const repaired = { ...result };

  // 修复grade_level
  if (!repaired.grade_level) {
    repaired.grade_level = gradeLevel;
  }

  // 修复score_breakdown
  if (!repaired.score_breakdown) {
    repaired.score_breakdown = {
      total_score: 0,
    };
  } else if (typeof repaired.score_breakdown.total_score !== 'number') {
    repaired.score_breakdown.total_score = 0;
  }

  // 修复corrections
  if (!Array.isArray(repaired.corrections) && !Array.isArray(repaired.detailed_corrections)) {
    repaired.corrections = [];
  }

  return repaired;
}

/**
 * 获取默认结果
 * @param {string} gradeLevel - 学段
 * @returns {Object} 默认结果结构
 */
function getDefaultResult(gradeLevel) {
  const base = {
    grade_level: gradeLevel,
    score_breakdown: {
      total_score: 0,
    },
    corrections: [],
    error_count: 0,
    error_categories: {},
  };

  if (gradeLevel === 'primary') {
    return {
      ...base,
      basic_stats: {
        word_count: 0,
        paragraph_count: 0,
        error_count: 0,
      },
      encouraging_comments: '抱歉，批改过程出现问题，请稍后重试。',
      improvement_suggestions: [],
      writing_tips: [],
    };
  } else if (gradeLevel === 'middle') {
    return {
      ...base,
      advanced_analysis: {},
      strength_analysis: '',
      weakness_analysis: '',
      specific_suggestions: [],
    };
  } else {
    return {
      ...base,
      college_entrance_standard: {},
      depth_analysis: {},
      artistic_evaluation: {},
      college_prep_suggestions: [],
      model_essay_comparison: '',
    };
  }
}

/**
 * 分类错误
 * @param {Array} errors - 错误数组
 * @returns {Object} 按类型分类的错误统计
 */
function categorizeErrors(errors) {
  const categories = {};

  errors.forEach((error) => {
    const type = error.type || 'unknown';
    if (!categories[type]) {
      categories[type] = 0;
    }
    categories[type]++;
  });

  return categories;
}

/**
 * 验证错误类型
 * @param {string} errorType - 错误类型
 * @returns {boolean} 是否是有效的错误类型
 */
export function isValidErrorType(errorType) {
  return Object.values(ERROR_CATEGORIES).includes(errorType);
}

/**
 * 验证严重程度
 * @param {string} severity - 严重程度
 * @returns {boolean} 是否是有效的严重程度
 */
export function isValidSeverity(severity) {
  return Object.values(SEVERITY_LEVELS).includes(severity);
}

/**
 * 获取解析统计信息
 * @param {Object} parsedResult - 解析后的结果
 * @returns {Object} 统计信息
 */
export function getParsingStats(parsedResult) {
  if (!parsedResult || !parsedResult.success) {
    return {
      success: false,
      error_count: 0,
      categories: {},
    };
  }

  return {
    success: true,
    score: parsedResult.data.final_score || 0,
    error_count: parsedResult.data.error_count || 0,
    categories: parsedResult.data.error_categories || {},
    grade_level: parsedResult.data.grade_level,
  };
}

export default {
  parseCorrection,
  validateResultFormat,
  extractErrors,
  calculateFinalScore,
  normalizeResult,
  isValidErrorType,
  isValidSeverity,
  getParsingStats,
  ERROR_CATEGORIES,
  SEVERITY_LEVELS,
};

